package com.qin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qin.common.Shuffle;
import com.qin.db.DBAccess;
import com.qin.entity.*;
import com.qin.enums.RetCode;
import com.qin.mapper.TestCaseMapper;
import com.qin.service.TestCaseService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class TestCaseServiceImpl implements TestCaseService {

    @Override
    public JSONObject queryTestCases(TestCase testCase){

//        System.out.println("service层：queryTestCases");

        //调用Dao层
        SqlSession sqlSession = null;
        Map map = new HashMap();
        JSONArray retArray;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            List retList = testCaseMapper.queryTestCases(testCase);
            retArray = new JSONArray(retList);

        } catch (Exception e) {
            e.printStackTrace();
            Map errMap = new HashMap();
            errMap.put("retCode", RetCode.ERROR.getCode());
            errMap.put("retMsg", RetCode.ERROR.getMsg());
            errMap.put("errorMsg", e.getMessage());
            JSONObject retJson = new JSONObject(errMap);

            return retJson;
        }  finally {
            if(sqlSession != null){
                sqlSession.close();
            }
        }

        //拼接返回JSON
        map.put("testCaseInfo", retArray);
        map.put("retCode", RetCode.SUCCESS.getCode());
        map.put("retMsg", RetCode.SUCCESS.getMsg());
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }

    @Override
    public JSONObject insertTestCase(TestCase testCase) {

//        System.out.println("service层：insertTestCase");

        //调用Dao层
        SqlSession sqlSession = null;
        Map map = new HashMap();
        boolean isSuccess;
        int max_order = -1;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            //查询公共函数下案例的最大序号
            max_order = testCaseMapper.queryMaxOrderByFunctionId(testCase.getFunction_id());
            //设置当前testCase对象的order_number
            if(max_order >= 0){
                testCase.setOrder_number(max_order + 1);
            }
            //插入记录
            isSuccess = testCaseMapper.insertTestCase(testCase);

        } catch (Exception e) {
            e.printStackTrace();
            Map errMap = new HashMap();
            errMap.put("retCode", RetCode.ERROR.getCode());
            errMap.put("retMsg", RetCode.ERROR.getMsg());
            errMap.put("errorMsg", e.getMessage());
            JSONObject retJson = new JSONObject(errMap);

            return retJson;
        } finally {
            if(sqlSession != null){
                sqlSession.commit();
                sqlSession.close();
            }
        }

        //拼接返回JSON
        if(isSuccess == true){
            map.put("retCode", RetCode.SUCCESS.getCode());
            map.put("retMsg", RetCode.SUCCESS.getMsg());
        }else{
            map.put("retCode", RetCode.ERROR.getCode());
            map.put("retMsg", RetCode.ERROR.getMsg());
            map.put("errorMsg", "执行sql出错或没有记录被插入");
        }
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }

    @Override
    public JSONObject deleteTestCase(TestCase testCase) {

//        System.out.println("service层：deleteTestCase");

        //调用Dao层
        SqlSession sqlSession = null;
        Map map = new HashMap();
        boolean isSuccess = false;
        int max_order = -1;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            //查询公共函数下案例的最大序号
            max_order = testCaseMapper.queryMaxOrderByFunctionId(testCase.getFunction_id());
            testCase.complete();

            //进行删除
            if(testCase.getOrder_number() > 0){
                //把待删除的TestCase的序号移动到List的最末尾
                TestCaseOrder testCaseOrder = new TestCaseOrder(testCase.getFunction_id(), testCase.getOrder_number(), max_order);
                reorderTestCases(testCaseOrder);

                //删除TestCase子组件SubComponent
                testCaseMapper.deleteTestCaseDetail_SubComponent(testCase.getComponentList());
                //删除TestCase组件Component
                testCaseMapper.deleteTestCaseDetail_Component(testCase.getComponentList());

                //删除TestCase基本信息
                isSuccess = testCaseMapper.deleteTestCase(testCase);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Map errMap = new HashMap();
            errMap.put("retCode", RetCode.ERROR.getCode());
            errMap.put("retMsg", RetCode.ERROR.getMsg());
            errMap.put("errorMsg", e.getMessage());
            JSONObject retJson = new JSONObject(errMap);

            return retJson;
        } finally {
            if(sqlSession != null){
                sqlSession.commit();
                sqlSession.close();
            }
        }

        //拼接返回JSON
        if(isSuccess == true){
            map.put("retCode", RetCode.SUCCESS.getCode());
            map.put("retMsg", RetCode.SUCCESS.getMsg());
        }else{
            map.put("retCode", RetCode.ERROR.getCode());
            map.put("retMsg", RetCode.ERROR.getMsg());
            map.put("errorMsg", "执行sql出错或没有记录被删除");
        }
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }

    @Override
    public JSONObject updateTestCase(TestCase testCase) {

//        System.out.println("service层：updateTestCase");

        //调用Dao层
        SqlSession sqlSession = null;
        Map map = new HashMap();
        boolean isSuccess;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            isSuccess = testCaseMapper.updateTestCase(testCase);

        } catch (Exception e) {
            e.printStackTrace();
            Map errMap = new HashMap();
            errMap.put("retCode", RetCode.ERROR.getCode());
            errMap.put("retMsg", RetCode.ERROR.getMsg());
            errMap.put("errorMsg", e.getMessage());
            JSONObject retJson = new JSONObject(errMap);

            return retJson;
        } finally {
            if(sqlSession != null){
                sqlSession.commit();
                sqlSession.close();
            }
        }

        //拼接返回JSON
        if(isSuccess == true){
            map.put("retCode", RetCode.SUCCESS.getCode());
            map.put("retMsg", RetCode.SUCCESS.getMsg());
        }else{
            map.put("retCode", RetCode.ERROR.getCode());
            map.put("retMsg", RetCode.ERROR.getMsg());
            map.put("errorMsg", "执行sql出错或没有记录被更新");
        }
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }

    @Override
    public JSONObject reorderTestCases(TestCaseOrder testCaseOrder) {

//        System.out.println("service层：reorderTestCases");

        //调用Dao层
        SqlSession sqlSession = null;
        Map map = new HashMap();
        boolean isSuccess = false;

        //定义调用Dao层的入参
        List<TestCaseOrder> testCaseOrderList = new ArrayList<TestCaseOrder>();

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            //查询公共函数下案例的最大序号
            int max_number = testCaseMapper.queryMaxOrderByFunctionId(testCaseOrder.getFunction_id());
            //重新排序
            Map shuffleMap = Shuffle.orderShuffle(1, max_number, testCaseOrder.getOld_order(), testCaseOrder.getNew_order());

            //遍历shuffleMap
            Iterator<Map.Entry<Integer, Integer>> it = shuffleMap.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<Integer, Integer> entry = it.next();
                //拼装testCaseOrderList
                if(entry.getKey() != entry.getValue()){
                    testCaseOrderList.add(new TestCaseOrder(testCaseOrder.getFunction_id(), entry.getKey(), entry.getValue()));
                }
            }
            for(int i=0; i<testCaseOrderList.size(); i++){
                System.out.println(testCaseOrderList.get(i));
            }
            //打印testCaseOrderList
            //案例序号重排
            if(testCaseOrderList.size() > 0){
                isSuccess = testCaseMapper.reorderTestCases(testCaseOrderList);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Map errMap = new HashMap();
            errMap.put("retCode", RetCode.ERROR.getCode());
            errMap.put("retMsg", RetCode.ERROR.getMsg());
            errMap.put("errorMsg", e.getMessage());
            JSONObject retJson = new JSONObject(errMap);

            return retJson;
        } finally {
            if(sqlSession != null){
                sqlSession.commit();
                sqlSession.close();
            }
        }

        //拼接返回JSON
        if(isSuccess == true){
            map.put("retCode", RetCode.SUCCESS.getCode());
            map.put("retMsg", RetCode.SUCCESS.getMsg());
        }else{
            map.put("retCode", RetCode.ERROR.getCode());
            map.put("retMsg", RetCode.ERROR.getMsg());
            map.put("errorMsg", "执行sql出错或没有记录被更新");
        }
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }

    @Override
    public int queryMaxOrderByFunctionId(String function_id) {

//        System.out.println("service层：queryMaxOrderByFunctionId");

        //调用Dao层
        SqlSession sqlSession = null;
        int max_number = -1;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            max_number = testCaseMapper.queryMaxOrderByFunctionId(function_id);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(sqlSession != null){
                sqlSession.commit();
                sqlSession.close();
            }
        }

        return max_number;
    }

    @Override
    public TestCase queryTestCaseByTestCaseId(TestCase testCase) {

//        System.out.println("service层：queryTestCaseByTestCaseId");

        //调用Dao层
        SqlSession sqlSession = null;
        TestCase testCase0 = null;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            testCase0 = testCaseMapper.queryTestCaseByTestCaseId(testCase);

        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            if(sqlSession != null){
                sqlSession.close();
            }
        }
        return testCase0;
    }

    @Override
    public JSONObject executeTestCase(ExecuteBean executeBean) {

        //执行组件内容
        TestCase testCase = new TestCase();
        testCase.setTestcase_id(executeBean.getTestcase_id());
        testCase.execute(executeBean);

        Map map = new HashMap();
        //拼接返回JSON
        map.put("retCode", RetCode.SUCCESS.getCode());
        map.put("retMsg", RetCode.SUCCESS.getMsg());
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }

    @Override
    public JSONObject queryTestCaseDetail(Component component) {

//        System.out.println("service层：queryTestCaseDetail");

        //调用Dao层
        SqlSession sqlSession = null;
        Map map = new HashMap();
        JSONArray retArray;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            List retList = testCaseMapper.queryTestCaseDetail(component);
            retArray = new JSONArray(retList);

        } catch (Exception e) {
            e.printStackTrace();
            Map errMap = new HashMap();
            errMap.put("retCode", RetCode.ERROR.getCode());
            errMap.put("retMsg", RetCode.ERROR.getMsg());
            errMap.put("errorMsg", e.getMessage());
            JSONObject retJson = new JSONObject(errMap);

            return retJson;
        }  finally {
            if(sqlSession != null){
                sqlSession.close();
            }
        }

        //拼接返回JSON
        map.put("componentInfo", retArray);
        map.put("retCode", RetCode.SUCCESS.getCode());
        map.put("retMsg", RetCode.SUCCESS.getMsg());
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }

    @Override
    public JSONObject saveTestCaseDetail(List<Component> componentList) {

//        System.out.println("service层：saveTestCaseDetail");

        //调用Dao层
        SqlSession sqlSession = null;
        Map map = new HashMap();
        boolean isSuccess = false;

        try {
            sqlSession = DBAccess.getSqlSession();
            TestCaseMapper testCaseMapper = sqlSession.getMapper(TestCaseMapper.class);

            //----------删除案例详细信息----------
            //删除子组件SubComponent
            testCaseMapper.deleteTestCaseDetail_SubComponent(componentList);
            //删除组件Component
            testCaseMapper.deleteTestCaseDetail_Component(componentList);

            //----------插入案例详细信息----------
            for(int i=0; i<componentList.size(); i++){
                //插入组件Component
                isSuccess = testCaseMapper.insertTestCaseDetail_Component(componentList.get(i));
                //获取刚刚插入的主键component_id
                String component_id = componentList.get(i).getComponent_id();

                //插入子组件SubComponent
                List<SubComponent> subComponentList = componentList.get(i).getSubComponentList();
                if(subComponentList != null){
                    for(int j=0; j<subComponentList.size(); j++){
                        //设置子组件的component_id属性
                        subComponentList.get(j).setComponent_id(component_id);
                    }
                    testCaseMapper.insertTestCaseDetail_SubComponent(subComponentList);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            Map errMap = new HashMap();
            errMap.put("retCode", RetCode.ERROR.getCode());
            errMap.put("retMsg", RetCode.ERROR.getMsg());
            errMap.put("errorMsg", e.getMessage());
            JSONObject retJson = new JSONObject(errMap);

            return retJson;
        }  finally {
            if(sqlSession != null){
                sqlSession.commit();
                sqlSession.close();
            }
        }

        //拼接返回JSON
        if(isSuccess == true){
            map.put("retCode", RetCode.SUCCESS.getCode());
            map.put("retMsg", RetCode.SUCCESS.getMsg());
        }else{
            map.put("retCode", RetCode.ERROR.getCode());
            map.put("retMsg", RetCode.ERROR.getMsg());
            map.put("errorMsg", "执行sql出错或没有记录被更新");
        }
        JSONObject retJson = new JSONObject(map);

        return retJson;
    }
}
